#!/usr/bin/python
# -*- coding: UTF-8 -*-

import sys
import os

global cwd
cwd = os.getcwd()
global abs_path
abs_path = os.path.abspath(os.path.dirname(__file__)) 
if cwd != abs_path:
    os.chdir(abs_path)

from util import *
from option import Options
import importlib
import getopt

global drivers
drivers = {}

global app_options
app_options = Options()

global build_type
build_type = "cpp"

for file in files(abs_path, "*.py"):
    if file.endswith("_driver.py"):
        (type, _) = os.path.basename(file).split("_")
        driver_name = os.path.splitext(os.path.basename(file))[0]
        initializer_mode = importlib.import_module(driver_name)
        builder_mod = importlib.import_module(driver_name)
        initializer_class = getattr(initializer_mode, "Initializer_" + type)
        builder_class = getattr(initializer_mode, "Builder_" + type)
        drivers[type] = {"initializer":initializer_class(app_options), "builder":builder_class(app_options)}
   
def usage():
    print("")
    print("    -h,--help                               help doc.")
    print("    -i,--init                               initialize repo.")
    print("    -a,--add IDL file                       add a IDL file to repo.")
    print("    -d,--delete IDL file                    delete a IDL file from repo.")
    print("    -b,--build IDL file[:service]           build all service in IDL file or build a service in IDL file")
    print("    -u,--update IDL file[:service]          update all service in IDL file or update a service in IDL file")
    print("    -l,--list                               show all installed IDL files")
    print("    -t,--type output type                   set output type")
    print('    -o,--option="key:value,..."             set option')
    print('    --update_root                           upgrade root')
    print('    --environment                           list environment')
    print('    --upgrade                               upgrade Repo. itself')    
def parseOptions():
    global drivers
    global app_options
    global build_type
    opts = None
    args = None
    try:
        opts,args = getopt.getopt(sys.argv[1:],'-t:-h-i-a:-u:-d:-b:-l-o:',['type=','help','init', 'add=', 'update=', "delete=", "build=", "list", "option=", "update_root", "environment"])
    except getopt.GetoptError as e:
        print(str(e))
        return
    initializer = None
    builder = None    
    if len(opts) == 0:
        usage()
    else:
        for opt, value in opts:
            if opt in ("-h", "--help"):
                usage()
                break
            if opt in ("-t", "--type"):
                build_type = value
                initializer = drivers[build_type]["initializer"]
                if not initializer.check():
                    print("Initialize Repo. failed")
                    return
                builder = drivers[build_type]["builder"]
            if opt in ("-o", "--option"):
                options = value.split(",")
                for option in options:
                    (key, value) = option.split(":", 1)
                    app_options.add_option(build_type, key, value)
            if opt in ("-i", "--init"):
                break
            if opt in ("-a", "--add"):
                builder.addIdl2Repo(value)
            elif opt in ("-u", "--update"):
                result = value.split(":", 1)
                if len(result) > 1:
                    builder.updateIdl(result[0], result[1])
                else:
                    builder.updateIdl(value)
            elif opt in ("--update_root"):
                builder.updateRoot()
            elif opt in ("-d", "--delete"):
                builder.deleteIdl(value)
            elif opt in ("-b", "--build"):
                result = value.split(":")
                if len(result) > 1:
                    builder.build_idl(result[0], result[1])
                else:
                    builder.build_idl(value)
            elif opt in ("-l", "--list"):
                idls = list_idl()
                for idl in idls:
                    print (idl)
            elif opt in ("--environment"):
                initializer.checkEnv()
            elif opt in ("--upgrade"):
                initializer.upgrade(value)
    
if __name__ == "__main__":
    #try:
    parseOptions()
    #except BaseException as e:
        #print(str(e))
    if cwd != abs_path:
        os.chdir(cwd)    

